﻿function showError(xhr) {
    throw new Error(xhr.responseText);
    //var errordlg = new MyAppDialog(700, 500, { modal: true });
    //var msg = $("<div/>");
    //msg.css("margin", "20px");
    //$(xhr.responseText).appendTo(msg);
    //errordlg.setContent("出错了", msg);
    //errordlg.show();
}

var pwddlg = new MyAppDialog(460, 320, { modal: true });
var querydlg = new MyAppDialog(1000, 650);

function showChangepwd() {
    pwddlg.setURL(csms_lang.message_info_title, baseurl + "Manage/User/ChangePassword");
    pwddlg.show();
}
function closeChangepwd() {
    pwddlg.close();
}

function handlerKeydown(target) {
    if (target == null) {
        $("input").bind("keydown", function (event) {
            if (event.keyCode == $.ui.keyCode.ENTER) {
                if ($(this).closest(".dialog").length > 0) {
                    event.preventDefault();
                    return false;
                }
            }
        });
    } else {
        $(target).find("input").bind("keydown", function (event) {
            if (event.keyCode == $.ui.keyCode.ENTER) {
                if ($(this).closest(".dialog").length > 0) {
                    event.preventDefault();
                    return false;
                }
            }
        });
    }
}

function addTitleFormatter(value, rec) {
    if (value) {
        return "<span title='" + value.replace(/\\/g, "\\\\").replace(/\'/g, '').replace(/\\t/g, '') + "'>" + value + "</span>";
    } else {
        return "";
    }
}

$(document).ready(function () {
    handlerKeydown(null);

    ////弹出框默认光标选中第一个输入框
    //$(".dialog-content input[type=text],.dialog-content select").eq(0).focus();

    $("ul.radio").each(function () {
        var radio = $(this);

        radio.find("input[type='radio']").click(function (evt) {
            evt.preventDefault();
            $(radio).find("input[type='hidden']").val($(this).val());
            $(radio).find("li.checked").removeClass("checked");
            $(this).parent("li").addClass("checked");
        });
    });

    $("[data-form=radio]").radio();
    $("[data-form=checkbox]").checkbox();
    $("[data-form=datepicker]").datepicker({ clearBtn: true, todayBtn: true, autoclose: true });
    $("[data-form=monthpicker]").datepicker({ clearBtn: true, startView: 1, minViewMode: 1, format: 'yyyy-mm', autoclose: true });
    $("[data-form=yearpicker]").datepicker({ clearBtn: true, startView: 2, minViewMode: 2, format: 'yyyy', autoclose: true });
    //$("[data-form=colorpicker]").colorpicker();
    $("[data-form=wycombo]").wycombo();
    $("[data-form=wyupload]").wyupload();

    //退出系统
    $("#exitsystem").click(function () {
        $.messager.confirm(csms_lang.message_confirm, csms_lang.message_quit_confirm, function (r) {
            if (r) {
                location.href = baseurl + "Member/Logout";
            }
        });
    });
    //语言
    $(".languagename").click(function () {
        setLanguage($(this).attr("data-lang"));
    });

    //定时器刷新消息
    startRefreshMessager();
});

function startRefreshMessager() {
    getMessager(function () {
        //刷新消息(间隔5s)
        setTimeout('startRefreshMessager()', 50000);
    });
}

function getMessager(_callback) {
    var $menu = $("#menu-messages");
    if ($menu.size() == 0) return;

    $.ajax({
        type: "post",
        url: baseurl + "Public/GetMessager",
        success: function (e) {
            if (e.Ret == "0") {
                //清除消息
                $menu.find(".messages-menu").find(".message-item").remove();

                if (e.Content.length == 0) {
                    $menu.find(".message-total").html("0");
                    $menu.find(".message-total").hide();
                    var $messager = $("<li class='message-item'><a href='#'><span class='test' style='color:#666;'>暂无新消息</span></a></li>");
                    $menu.find(".messages-menu").append($messager);
                } else {
                    var msgcount = 0;
                    $.each(e.Content, function (index, item) {
                        var $messager = $("<li class='message-item'></li>");
                        var $href = $("<a href='" + item.Url + "'><span class='text'>" + item.Message + "</span><span class='label label-danger label-message'>" + item.MsgCount + "</span></a>");
                        $href.appendTo($messager);
                        $menu.find(".messages-menu").append($messager);
                        msgcount += item.MsgCount;
                    });

                    $menu.find(".message-total").html(msgcount);
                    $menu.find(".message-total").show();
                }
            }
            if (_callback) _callback();
        },
        error: function (e) {
            if (_callback) _callback();
        }
    });
}

function setLanguage(lang) {
    $.ajax({
        type: "post",
        url: baseurl + "Public/SetLanguage",
        data: {
            lang: lang
        },
        success: function (e) {
            if (e.Ret == "0") {
                location.href = location.href;
                location.reload();
            }
        }
    });
}

function MyAppDialog(width, height, options) {
    this.setting = {
        width: width,
        height: height,
        //top: "10%",
        closed: true,
        maximizable: false,
        resizable: true,
        modal: true,
        draggable: true,
        onClose: function () {
            $(this).dialog("destroy");
        }
    };

    $.extend(this.setting, options);
}

MyAppDialog.prototype.setSize = function (width, height) {
    this.setting.width = width;
    this.setting.height = height;
}

MyAppDialog.prototype.setTop = function (top) {
    //this.setting.top = top;
}

MyAppDialog.prototype.setTitle = function (title) {
    this.setting.title = title;
    if (this.dlg) {
        this.dlg.dialog("setTitle", title);
    }
}

MyAppDialog.prototype.setURL = function (title, url) {
    this.setting.title = title;
    this.setting.content = "<iframe id='iframe' frameborder='0' scrolling='auto' class='easyui-layout layout' data-options='fit:true' src='" + url + "'></iframe>";
}

MyAppDialog.prototype.setAjaxURL = function (title, url) {
    this.setting.title = title;
    this.setting.href = url;
}

MyAppDialog.prototype.setContent = function (title, content) {
    this.setting.title = title;
    this.setting.content = content;
}

MyAppDialog.prototype.show = function () {
    if (this.dlg != null && this.dlg != undefined) {
        try {
            this.dlg.dialog("close");
        } catch (e) { }
    }

    //if (this.setting.top == undefined) {
    if (this.setting.height) {
        if ($(window).height() < this.setting.height) {
            this.setting.top = 0;
            //窗口高度不能超过整个页面高度
            this.setting.height = $(window).height();
        } else {
            this.setting.top = undefined;//($(window).height() - this.setting.height) * 0.5;
        }
    }
    //}
    //this.setting.top = 30;

    this.dlg = $("<div />").dialog(this.setting).dialog("open");

    var $dlg = this.dlg;

    $(window).bind("scroll", function () {
        try {
            var top = ($(window).height() - $dlg.dialog("options").height) / 2;
            if (top < 0) top = 0;
            $dlg.dialog("move", { top: top + $(document).scrollTop() });
        } catch (e) { }
    });
}

MyAppDialog.prototype.close = function () {
    this.setting.top = undefined;
    if (this.dlg)
        this.dlg.dialog("close");

    $(window).unbind("scroll");
}

String.prototype.format = function (args) {
    var result = this;
    if (arguments.length > 0) {
        if (arguments.length == 1 && typeof (args) == "object") {
            for (var key in args) {
                if (args[key] != undefined) {
                    var reg = new RegExp("({" + key + "})", "g");
                    result = result.replace(reg, args[key]);
                }
            }
        }
        else {
            for (var i = 0; i < arguments.length; i++) {
                if (arguments[i] != undefined) {
                    //var reg = new RegExp("({[" + i + "]})", "g");//这个在索引大于9时会有问题，谢谢何以笙箫的指出
                    var reg = new RegExp("({)" + i + "(})", "g");
                    result = result.replace(reg, arguments[i]);
                }
            }
        }
    }
    return result;
}
String.prototype.trim = function () {
    return this.replace(/(^\s*)|(\s*$)/g, "");
}
String.prototype.ltrim = function () {
    return this.replace(/(^\s*)/g, "");
}
String.prototype.rtrim = function () {
    return this.replace(/(\s*$)/g, "");
}
Date.prototype.format = function (format) {
    var o = {
        "M+": this.getMonth() + 1, //month
        "d+": this.getDate(),    //day
        "h+": this.getHours(),   //hour
        "m+": this.getMinutes(), //minute
        "s+": this.getSeconds(), //second
        "q+": Math.floor((this.getMonth() + 3) / 3),  //quarter
        "S": this.getMilliseconds() //millisecond
    };
    if (/(y+)/.test(format)) {
        format = format.replace(RegExp.$1,
			(this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(format))
            format = format.replace(RegExp.$1,
				RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
    }
    return format;
}
/* 得到日期年月日等加数字后的日期 */
Date.prototype.dateAdd = function (interval, number) {
    var d = this;
    var k = { 'y': 'FullYear', 'q': 'Month', 'm': 'Month', 'w': 'Date', 'd': 'Date', 'h': 'Hours', 'n': 'Minutes', 's': 'Seconds', 'ms': 'MilliSeconds' };
    var n = { 'q': 3, 'w': 7 };
    eval('d.set' + k[interval] + '(d.get' + k[interval] + '()+' + ((n[interval] || 1) * number) + ')');
    return d;
}

/*easyui tree扩展*/
$(function () {
    //此处是扩展tree的两个方法. 
    $.extend($.fn.tree.methods, {
        //注：getChildren是获取所有子节点（包括子节点的子节点）
        //获取下一级的子节点
        getLeafChildren: function (jq, params) {
            var nodes = [];
            $(params).next().children().children("div.tree-node").each(function () {
                nodes.push($(jq[0]).tree('getNode', this));
            });
            return nodes;
        },
        //扩展getChecked方法,使其能实心节点也一起返回 
        getCheckedExt: function (jq) {
            var checked = $(jq).tree("getChecked");
            var checkbox2 = $(jq).find("span.tree-checkbox2").parent();
            $.each(checkbox2, function () {
                var node = $(jq[0]).tree('getNode', this);
                checked.push(node);
            });
            return checked;
        },
        //扩展一个能返回实心节点的方法 
        getSolidExt: function (jq) {
            var checked = [];
            var checkbox2 = $(jq).find("span.tree-checkbox2").parent();
            $.each(checkbox2, function () {
                var node = $(jq[0]).tree('getNode', this);
                checked.push(node);
            });
            return checked;
        },
        /**
         * 激活复选框  
         * @param {Object} jq  
         * @param {Object} target  
         */
        enableCheck: function (jq, target) {
            return jq.each(function () {
                var realTarget = null;
                if (typeof target == "string" || typeof target == "number") {
                    var node = $(this).tree("find", target);
                    if (node != null && node != undefined) {
                        realTarget = node.target;
                    }
                } else {
                    realTarget = target;
                }
                if (realTarget == null || realTarget == undefined) return;

                var ckSpan = $(realTarget).find(">span.tree-checkbox");
                if (ckSpan.hasClass('tree-checkbox-disabled0')) {
                    ckSpan.removeClass('tree-checkbox-disabled0');
                } else if (ckSpan.hasClass('tree-checkbox-disabled1')) {
                    ckSpan.removeClass('tree-checkbox-disabled1');
                } else if (ckSpan.hasClass('tree-checkbox-disabled2')) {
                    ckSpan.removeClass('tree-checkbox-disabled2');
                }
            });
        },
        /**
         * 禁用复选框  
         * @param {Object} jq  
         * @param {Object} target  
         */
        disableCheck: function (jq, target) {
            return jq.each(function () {
                var realTarget = null;
                var that = this;
                var state = $.data(this, 'tree');
                var opts = state.options;
                if (typeof target == "string" || typeof target == "number") {
                    var node = $(this).tree("find", target);
                    if (node != null && node != undefined) {
                        realTarget = node.target;
                    }
                } else {
                    realTarget = target;
                }
                if (realTarget == null || realTarget == undefined) return;

                var ckSpan = $(realTarget).find(">span.tree-checkbox");
                ckSpan.removeClass("tree-checkbox-disabled0").removeClass("tree-checkbox-disabled1").removeClass("tree-checkbox-disabled2");
                if (ckSpan.hasClass('tree-checkbox0')) {
                    ckSpan.addClass('tree-checkbox-disabled0');
                } else if (ckSpan.hasClass('tree-checkbox1')) {
                    ckSpan.addClass('tree-checkbox-disabled1');
                } else {
                    ckSpan.addClass('tree-checkbox-disabled2')
                }
                if (!state.resetClick) {
                    $(this).unbind('click').bind('click', function (e) {
                        var tt = $(e.target);
                        var node = tt.closest('div.tree-node');
                        if (!node.length) { return; }
                        if (tt.hasClass('tree-hit')) {
                            $(this).tree("toggle", node[0]);
                            return false;
                        } else if (tt.hasClass('tree-checkbox')) {
                            if (tt.hasClass('tree-checkbox-disabled0') || tt.hasClass('tree-checkbox-disabled1') || tt.hasClass('tree-checkbox-disabled2')) {
                                $(this).tree("select", node[0]);
                            } else {
                                if (tt.hasClass('tree-checkbox1')) {
                                    $(this).tree('uncheck', node[0]);
                                } else {
                                    $(this).tree('check', node[0]);
                                }
                                return false;
                            }
                        } else {
                            $(this).tree("select", node[0]);
                            opts.onClick.call(this, $(this).tree("getNode", node[0]));
                        }
                        e.stopPropagation();
                    });
                }

            });
        }
    });
});

/*eayui扩展，layout折叠后显示数据源*/
(function ($) {
    var buttonDir = { north: 'down', south: 'up', east: 'left', west: 'right' };
    $.extend($.fn.layout.paneldefaults, {
        onBeforeCollapse: function () {
            /**/
            var popts = $(this).panel('options');
            var dir = popts.region;
            var btnDir = buttonDir[dir];
            if (!btnDir) return false;

            setTimeout(function () {
                var pDiv = $('.layout-button-' + btnDir).closest('.layout-expand').css({
                    textAlign: 'center', lineHeight: '18px', fontWeight: 'bold'
                });

                if (popts.title) {
                    var vTitle = popts.title;
                    if (dir == "east" || dir == "west") {
                        var vTitle = popts.title.split('').join('<br/>');
                        pDiv.find('.panel-body').html(vTitle);
                    } else {
                        $('.layout-button-' + btnDir).closest('.layout-expand').find('.panel-title')
                        .css({ textAlign: 'left' })
                        .html(vTitle)
                    }

                }
            }, 100);

        }
    });
})(jQuery);

//禁止右键、复制功能
(function ($) {
    $.fn.ctrlCmd = function (key) {

        var allowDefault = true;

        if (!$.isArray(key)) {
            key = [key];
        }

        return this.keydown(function (e) {
            for (var i = 0, l = key.length; i < l; i++) {
                if (e.keyCode === key[i].toUpperCase().charCodeAt(0) && e.metaKey) {
                    allowDefault = false;
                }
            };
            return allowDefault;
        });
    };


    $.fn.disableSelection = function () {

        this.ctrlCmd(['a', 'c']);

        return this.attr('unselectable', 'on')
                   .css({
                       '-moz-user-select': '-moz-none',
                       '-moz-user-select': 'none',
                       '-o-user-select': 'none',
                       '-khtml-user-select': 'none',
                       '-webkit-user-select': 'none',
                       '-ms-user-select': 'none',
                       'user-select': 'none'
                   })
                   .bind('selectstart', false);
    };

})(jQuery);

var APP = {
    _msg: {}, //alert message
    _set: {
        loginUrl: "", //session timeout
        loginTitle: "", //if loginTitle open a login dialog
        debug: true
    },
    msg: function (key, args) {
        var _format = function (str, args) {
            args = args || [];
            var result = str || "";
            for (var i = 0; i < args.length; i++) {
                result = result.replace(new RegExp("\\{" + i + "\\}", "g"), args[i]);
            }
            return result;
        }
        return _format(this._msg[key], args);
    },
    debug: function (msg) {
        if (this._set.debug) {
            if (typeof (console) != "undefined") console.log(msg);
            else alert(msg);
        }
    }
};

//json日期格式转换为正常格式
function jsonDateFormat(jsonDate) {
    try {//出自http://www.cnblogs.com/ahjesus 尊重作者辛苦劳动成果,转载请注明出处,谢谢!
        var date = new Date(parseInt(jsonDate.replace("/Date(", "").replace(")/", ""), 10));
        var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
        var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
        var hours = date.getHours();
        var minutes = date.getMinutes();
        var seconds = date.getSeconds();
        var milliseconds = date.getMilliseconds();
        return date.getFullYear() + "-" + month + "-" + day;
    } catch (ex) {//出自http://www.cnblogs.com/ahjesus 尊重作者辛苦劳动成果,转载请注明出处,谢谢!
        return "";
    }
}
//json日期格式转换为正常格式
function jsonTimeFormat(jsonDate) {
    try {//出自http://www.cnblogs.com/ahjesus 尊重作者辛苦劳动成果,转载请注明出处,谢谢!
        var date = new Date(parseInt(jsonDate.replace("/Date(", "").replace(")/", ""), 10));
        var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
        var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
        var hours = date.getHours();
        var minutes = date.getMinutes();
        var seconds = date.getSeconds();
        var milliseconds = date.getMilliseconds();
        return date.getFullYear() + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;// + "." + milliseconds;
    } catch (ex) {//出自http://www.cnblogs.com/ahjesus 尊重作者辛苦劳动成果,转载请注明出处,谢谢!
        return "";
    }
}

// 获取长度为len的随机字符串  
function getRandomString(len) {
    len = len || 32;
    var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'; // 默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1  
    var maxPos = $chars.length;
    var pwd = '';
    for (i = 0; i < len; i++) {
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}

function setCookie(name, value) {
    var Days = 30;
    var exp = new Date();
    exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
    document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString();
}
//读取COOKIES
function getCookie(name) {
    var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
    if (arr = document.cookie.match(reg)) return unescape(arr[2]);
    else return null;
}
//删除COOKIES
function delCookie(name) {
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval = getCookie(name);
    if (cval != null) document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
}

function beforeFrameHtmlUnload() {
    var a = beforeFrameHtmlUnload._oFuncs, b;
    for (var c in a) {
        b = (typeof a[c] == "function") && a[c]();
        if (b) {
            return b;
        }
    }
}
beforeFrameHtmlUnload.add = function (b, a) {
    beforeFrameHtmlUnload._oFuncs[b] = a;
};
beforeFrameHtmlUnload._oFuncs = {};
beforeFrameHtmlUnload.remove = function (a) {
    delete beforeFrameHtmlUnload._oFuncs[a];
};

//if (window.attachEvent) {
//    window.attachEvent('onbeforeunload', beforeFrameHtmlUnload);
//} else {
//    window.addEventListener('beforeunload', beforeFrameHtmlUnload, false);
//}

$(window).on('beforeunload', beforeFrameHtmlUnload);